package com.smartlink.app.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.io.IOException;

/**
 * 获取网络状态
 * Created by Administrator on 2016/7/1.
 */
public class NetWorkUtil {
    private static final String TAG = "NetWorkUtil";

    /**
     * 检查网络是否可用
     *
     * @param ctx
     * @return
     */
    public static boolean isNetworkConnected(Context ctx) {
        if (ctx != null) {
            ConnectivityManager manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 首先检查wifi是否可用
     * 检查是否是ESP8266的wifi
     *
     * @param ctx
     * @return true  是定制设备WIFI
     */
    public static boolean isDeviceWifiConnected(Context ctx) {
        if (ctx != null) {
            WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {
                boolean isWifiEnabled = wifiManager.isWifiEnabled();
                if (isWifiEnabled) {
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String ssid = wifiInfo.getSSID();
                    Log.i(TAG, "isDeviceWifiConnected: " + ssid);
                    if ("\"ESP8266\"".equals(ssid)) {
                        return true;
                    }
                }
            }
            return false;
        }
        return false;
    }

    /**
     * ping  ip地址
     *
     * @param ip
     * @return
     */
    public static boolean pingIP(String ip) {
        boolean pingFlag = false;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("ping -c 1 -i 0.2 -W 3 " + ip);
            int status = process.waitFor();
            if (status == 0) {
                pingFlag = true;
            } else {
                pingFlag = false;
            }
        } catch (Exception e) {
            pingFlag = false;
            e.printStackTrace();
        } finally {
            process.destroy();
        }
        return pingFlag;
    }


}
